﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Pool : MonoBehaviour {
    

    public UnityEngine.GameObject template;

    HashSet<UnityEngine.GameObject> activeSet = new HashSet<UnityEngine.GameObject>();
    Stack<UnityEngine.GameObject> inactiveStack = new Stack<UnityEngine.GameObject>();

    public void SetTemplate(UnityEngine.GameObject go)
    {
        this.template = go;
    }

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    public UnityEngine.GameObject Gen()
    {
        if (inactiveStack.Count == 0)
        {
            var go = UnityEngine.GameObject.Instantiate(template);
            go.transform.SetParent(transform);
            go.transform.localPosition = Vector3.zero;
            go.SetActive(true);
            activeSet.Add(go);
            return go;
        }
        else
        {
            var go = inactiveStack.Pop();
            go.SetActive(true);
            activeSet.Add(go);
            return go;
        }
    }

    public void Recycle(UnityEngine.GameObject go)
    {
        activeSet.Remove(go);
        inactiveStack.Push(go);
        go.SetActive(false);
    }

    public void Clear()
    {
        foreach (var go in activeSet)
        {
            Destroy(go);
        }

        activeSet.Clear();
    }
}
